package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConst;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.entity.Result;
import com.itheima.pojo.CheckGroup;
import com.itheima.pojo.Member;
import com.itheima.pojo.SysUser;
import com.itheima.service.UserService;
import com.itheima.utils.MD5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author 黑马程序员
 * @Company http://www.ithiema.com
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Reference
    UserService userService;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;


    @RequestMapping("/doSuccess")
    public String doSuccess(){
        return "redirect:http://localhost:83/pages/main.html";
    }


    @RequestMapping("/doFail")
    public String doFail(){
        return "redirect:http://localhost:83/login.html?message=loginFail";
    }


    @RequestMapping("/getUsername")
    @ResponseBody
    public Result getUsername(HttpServletRequest request){
//        获取session中所有的 key  SPRING_SECURITY_CONTEXT
//        获取枚举类型
//        Enumeration attributeNames = request.getSession().getAttributeNames();
//        遍历枚举类型
//        while(attributeNames.hasMoreElements()){
//            System.out.println(attributeNames.nextElement());
//        }
        String username = null;
        try {
//        安全框架提供一个工具类，可以直接获取session中的对象（安全框架的上下文对象）
            SecurityContext context = SecurityContextHolder.getContext();
//        认证对象
            Authentication authentication = context.getAuthentication();
//        获取principal(重要的)
            Object principal = authentication.getPrincipal();
//        如果认证失败，principal获取到的是一个字符串，转换为User时，会抛出异常
//        把principal转换为User类型
            User user = (User) principal;
            //获取username
            username = user.getUsername();
            return new Result(true, MessageConst.GET_USERNAME_SUCCESS, username);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.GET_USERNAME_FAIL);
        }

    }

    @RequestMapping("/findPage")
    @ResponseBody
    public PageResult findPage(@RequestBody QueryPageBean queryPageBean){
        return userService.pageQuery(queryPageBean);
    }

    @RequestMapping("/add")
    @ResponseBody
    public Result add(Integer[] roleIds, @RequestBody SysUser sysUser){
        try {
            String passwords = sysUser.getPassword();
            passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode(passwords);
            sysUser.setPassword(password);
            userService.add(sysUser,roleIds);
            return new Result(true, MessageConst.ADD_SYSUSER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConst.ADD_SYSUSER_FAIL);

        }
    }

    @RequestMapping("/findById")
    @ResponseBody
    public Result findById(Integer id){
        try {
            SysUser sysUser = userService.findById(id);
            return new Result(true,MessageConst.QUERY_SYSISER_SUCCESS, sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_SYSUSER_FAIL);
        }
    }

    @RequestMapping("/findRoleIdsById")
    @ResponseBody
    public Result findRoleIdsById(Integer id){
        try {
            List<Integer> roleIds = userService.findRoleIdsById(id);
            return new Result(true,MessageConst.QUERY_SYSISER_SUCCESS, roleIds);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.QUERY_SYSUSER_FAIL);
        }
    }

    @RequestMapping("/edit")
    @ResponseBody
    public Result edit(Integer[] roleIds, @RequestBody SysUser sysUser){
        try {
            String passwords = sysUser.getPassword();
            passwordEncoder = new BCryptPasswordEncoder();
            String password = passwordEncoder.encode(passwords);
            sysUser.setPassword(password);
            userService.edit(sysUser,roleIds);
            return new Result(true,MessageConst.EDIT_SYSUSER_SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.EDIT_SYSUSER_FAIL);
        }
    }

    @RequestMapping("/delById")
    @ResponseBody
    public Result delById(Integer id){
        try {
            userService.delById(id);
            return new Result(true,MessageConst.DELETE_SYSUSER_SUCCESS);
        }catch (RuntimeException e) {
            e.printStackTrace();
            return new Result(false,e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConst.DELETE_SYSUSER_FAIL);
        }
    }

}
